<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="区域名称" prop="regionName">
        <el-input
          v-model="queryParams.regionName"
          placeholder="请输入区域名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['duty:region:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['safe:devise:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-top"
          size="mini"
          @click="UpDataList"
          :disabled="disabledButton"
          v-hasPermi="['duty:region:add']"
          >上移</el-button
        >
        <el-button
          :disabled="disabledButton"
          type="primary"
          plain
          icon="el-icon-bottom"
          size="mini"
          @click="DownDataList"
          v-hasPermi="['duty:region:add']"
          >下移</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
          >展开/折叠</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="regionList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="区域名称" align="left" prop="regionName" />
      <el-table-column
        label="问题整改人"
        align="center"
        prop="correctorUserName"
      />
      <el-table-column
        label="问题通知人"
        align="center"
        prop="notifierUserName"
      />
      <el-table-column
        label="问题复核人"
        align="center"
        prop="reviewerUserName"
      />
      <el-table-column label="分包单位" align="center" prop="cooperatorId">
        <template slot-scope="scope">
          <el-tag
            v-for="(item, index) in scope.row.cooperatorId"
            :key="index"
            :type="item.type"
            effect="plain"
          >
            {{ item }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="说明" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['duty:region:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleLook(scope.row)"
            v-hasPermi="['duty:region:add']"
            >查看</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['duty:region:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 查看/添加或修改责任区域对话框 -->
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="open"
      width="750px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="编码" prop="code">
          <el-input
            :disabled="disabled"
            v-model="form.code"
            placeholder="请输入编码"
          />
        </el-form-item>
        <el-form-item label="所属区域" prop="parentId">
          <treeselect
            :disabled="disabled"
            v-model="form.parentId"
            :options="regionOptions"
            :normalizer="normalizer"
            placeholder="请选择所属区域"
          />
        </el-form-item>
        <el-form-item label="区域名称" prop="regionName">
          <el-input
            :disabled="disabled"
            v-model="form.regionName"
            placeholder="请输入区域名称"
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="问题整改人" prop="correctorUserId">
              <el-select
                :disabled="disabled"
                style="width: 253px"
                v-model="form.correctorUserId"
                placeholder="请输入问题整改人"
              >
                <el-option
                  v-for="item in correctorUserIdData"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="问题通知人" prop="notifierUserId">
              <el-select
                :disabled="disabled"
                style="width: 253px"
                v-model="form.notifierUserId"
                placeholder="请输入问题通知人"
              >
                <el-option
                  v-for="item in correctorUserIdData"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="问题复核人" prop="reviewerUserId">
              <el-select
                :disabled="disabled"
                style="width: 253px"
                v-model="form.reviewerUserId"
                placeholder="请输入问题复核人"
              >
                <el-option
                  v-for="item in correctorUserIdData"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="分包单位" prop="cooperatorIds">
              <el-select
                :disabled="disabled"
                style="width: 253px"
                multiple
                v-model="form.cooperatorIds"
                placeholder="请选择分包单位"
              >
                <el-option
                  v-for="item in packageRegionData"
                  :key="item.id"
                  :label="item.enterpriseName"
                  :value="item.id"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
        </el-row>
        <el-form-item label="说明" prop="remark">
          <el-input
            :disabled="disabled"
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRegion,
  getRegion,
  delRegion,
  addRegion,
  updateRegion,
  packageRegion,
  moveDataList,
} from "@/api/biz/duty/region";
import { listUser } from "@/api/common/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { mapState } from "vuex";
export default {
  name: "Region",
  components: {
    Treeselect,
  },
  data() {
    return {
      disabledButton: false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 责任区域表格数据
      regionList: [],
      // 责任区域树选项
      regionOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        projectId: this.$store.state.app.selectData,
        regionName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: "项目id不能为空", trigger: "blur" },
        ],
        regionName: [
          { required: true, message: "区域名称不能为空", trigger: "blur" },
        ],
        parentId: [
          { required: true, message: "父id不能为空", trigger: "blur" },
        ],
        code: [
          { required: true, message: "编码不能为空", trigger: "blur" },
          { max: 100, message: "编码最多为100个字符", trigger: "blur" },
        ],
      },
      correctorUserIdData: null,
      packageRegionData: null,
      disabled: false,
    };
  },
  created() {
    this.getList();
  },
  computed: {
    ...mapState(["app"]),
  },
  watch: {
    app: {
      handler(newVal, oldVal) {
        this.queryParams.projectId = newVal.selectData;
        this.getList();
      },
      deep: true,
    },
    ids: {
      handler(newVal, oldVal) {
        if (newVal.length > 1) {
          this.disabledButton = true;
        } else {
          this.disabledButton = false;
        }
      },
      deep: true,
    },
  },
  methods: {
    /** 查询责任区域列表 */
    getList() {
      this.loading = true;
      listRegion(this.queryParams).then((response) => {
        this.regionList = this.handleTree(response.data, "id", "parentId");
        this.loading = false;
      });
    },
    /** 转换责任区域数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.regionName,
        children: node.children,
      };
    },
    /** 查询新增各数据下拉 */
    getTreeselect() {
      listRegion(this.queryParams).then((response) => {
        this.regionOptions = [];
        const data = { id: 0, regionName: "顶级节点", children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.regionOptions.push(data);
      });
      listUser(this.queryParams).then((response) => {
        this.correctorUserIdData = response.rows;
      });
      packageRegion().then((response) => {
        this.packageRegionData = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectId: null,
        regionName: null,
        parentId: null,
        correctorUserId: null,
        notifierUserId: null,
        reviewerUserId: null,
        cooperatorId: null,
        remark: null,
        sort: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      if (this.queryParams.projectId == null) {
        this.$message({
          message: "请选择项目部后再点击添加！",
          type: "warning",
        });
      } else {
        this.reset();
        this.getTreeselect();
        if (row != null && row.id) {
          this.form.parentId = row.id;
        } else {
          this.form.parentId = 0;
        }
        this.disabled = false;
        this.open = true;
        this.title = "添加责任区域";
      }
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.parentId;
      }
      getRegion(row.id).then((response) => {
        this.form = response.data;
        this.disabled = false;
        this.open = true;
        this.title = "修改责任区域";
      });
    },
    /**查看 */
    handleLook(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.parentId;
      }
      getRegion(row.id).then((response) => {
        this.form = response.data;
        this.disabled = true;
        this.open = true;
        this.title = "修改责任区域";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateRegion(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.projectId = this.queryParams.projectId;
            addRegion(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除责任区域编号为"' + ids + '"的数据项？')
        .then(function () {
          return delRegion(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
          this.$message({
          message: '删除失败：请确认是否存在子节点！',
          type: 'warning'
        });
        });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /**上移 */
    UpDataList() {
      if (this.ids.length < 1) {
        this.$message({
          message: "请选择要移动的数据",
          type: "warning",
        });
      } else {
        const moveType = {
          id: this.ids[0],
          moveType: 1,
        };
        moveDataList(moveType).then(() => {
          this.getList();
        });
      }
    },
    /**下移 */
    DownDataList() {
      if (this.ids.length < 1) {
        this.$message({
          message: "请选择要移动的数据",
          type: "warning",
        });
      } else {
        const moveType = {
          id: this.ids[0],
          moveType: 2,
        };
        moveDataList(moveType).then(() => {
          this.getList();
        });
      }
    },
  },
};
</script>
